//
//  LoginViewController.m
//  ClassRoom
//
//  Created by apple on 12-11-27.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "ASIHTTPRequest.h"
#import "UrlData.h"
#import "JSONKit.h"
#import "RegisterViewController.h"
#import "HomePageViewController.h"
#import "LoginStatus.h"
#import "UserCenterViewController.h"
#import "SFHFKeychainUtils.h"
#import "Notifications.h"



@interface LoginViewController ()


@end
@implementation LoginViewController
@synthesize emailSaved,passWordSaved;
@synthesize userInformation;
@synthesize userName,address,focus;
@synthesize status;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"登陆";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _toolBar.tintColor =[UIColor colorWithRed:23.0/250.f green:164.0/250.f blue:66.0/250.f alpha:1.0f];
    status=0;
    NSError *error;
    checked = [SFHFKeychainUtils getPasswordForUsername:@"checked"
                                         andServiceName:ClassRoom_URL 
                                                  error:&error];
    
    
    
    
    [self setView];
}

- (void)setView{
    NSError *error;
    UIImageView *emailImageView = [[UIImageView alloc] initWithFrame:CGRectMake(36, 112+44, 235, 42)];
    emailImageView.image = [UIImage imageNamed:@"235-42"];
    [self.view addSubview:emailImageView];
    [emailImageView release];
    
    UIImageView *passWordImageView = [[UIImageView alloc] initWithFrame:CGRectMake(36, 169+44, 235, 42 )];
    passWordImageView.image = [UIImage imageNamed:@"235-42"];
    [self.view addSubview:passWordImageView];
    [passWordImageView release];
    
    _emailName.text = @"邮箱/昵称";
    _emailName.textColor = [UIColor whiteColor];
    _emailName.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:_emailName];
    
    _passWord.text = @"密   码";
    _passWord.textColor = [UIColor whiteColor];
    _passWord.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:_passWord];
    
    
    if (nil != checked) {
        emailSaved = [SFHFKeychainUtils getPasswordForUsername:@"userName"
                                                andServiceName:ClassRoom_URL
                                                         error:&error];
    }
    _emailTextField.backgroundColor = [UIColor clearColor];
    _emailTextField.text = emailSaved;
    [self.view addSubview:_emailTextField];
    
    
    if (nil != checked) {
        passWordSaved = [SFHFKeychainUtils getPasswordForUsername:[NSString stringWithFormat:@"%@",_emailTextField.text] 
                                                   andServiceName:ClassRoom_URL
                                                            error:&error];
        [_rememberPassWord setImage:[UIImage imageNamed:@"checked"] forState:UIControlStateNormal];
    }
    _passWordTextField.secureTextEntry = YES;
    _passWordTextField.backgroundColor = [UIColor clearColor];
    _passWordTextField.text = passWordSaved;
    [self.view addSubview:_passWordTextField];
}

- (void)viewDidUnload
{
    [_passWord release];
    _passWord = nil;
    [_emailName release];
    _emailName = nil;
    [_emailTextField release];
    _emailTextField = nil;
    [_passWordTextField release];
    _passWordTextField = nil;
    [_weiboBarButtonItem release];
    _weiboBarButtonItem = nil;
    [_renrenBarButtonItem release];
    _renrenBarButtonItem = nil;
    [_QQBarButtonItem release];
    _QQBarButtonItem = nil;
    [_rememberPassWord release];
    _rememberPassWord = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

#pragma mark -
#pragma mark Button点击方法事件

- (IBAction)cancelSelfController:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)registerButton:(id)sender {
    RegisterViewController *registerViewController = [[[RegisterViewController alloc] init] autorelease];
    [self presentViewController:registerViewController animated:YES completion:nil];
}



- (IBAction)loginButton:(id)sender {
    NSString *urlstr=[NSString stringWithFormat:@"%@%@%@%@&%@%@",ClassRoom_URL,LOGIN_URL,ClassRoom_EMAIL_URL,_emailTextField.text,ClassRoom_PASSWORD_URL,_passWordTextField.text];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    [request startAsynchronous];//设置为异步请求
}

- (void)requestFinished:(ASIHTTPRequest *)request{
    // 当以文本形式读取返回内容时用这个方法
    NSString *responseString = [request responseString];
    NSDictionary *loginDic = [[responseString objectFromJSONString] retain];
    
    NSLog(@"loginDic = %@",loginDic);

    NSString *error = [loginDic objectForKey:@"error"];
    userInformation = [[NSDictionary alloc] initWithDictionary:(NSDictionary *)[loginDic objectForKey:@"userInformation"]];
    [self loginDataOpinion:error];
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    NSError *error = [request error];
    NSLog(@"%@",error);
}

- (void)loginDataOpinion:(NSString *)error{
    if ([error intValue] == -2) {
        UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您输入的密码有误,请查证后输入" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [al show];
        [al release];
    }
    if ([error intValue] == -1) {
        UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您的邮箱或者密码错误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [al show];
        [al release];
    }
    if([error intValue]==0){
        [LoginStatus sharedLoginStatus].ifLogined=TRUE;
        [LoginStatus LoginedUserID].userID = [NSString stringWithFormat:@"%@",[userInformation objectForKey:@"userID"]];
        NSLog(@"%@",[LoginStatus LoginedUserID].userID);
        
        self.userName = [NSString stringWithFormat:@"%@",[userInformation objectForKey:@"userName"]];
        self.address = [NSString stringWithFormat:@"%@",[userInformation objectForKey:@"address"]];
        self.focus =  [NSString stringWithFormat:@"%@",[userInformation objectForKey:@"focus"]];
        
        
        NSError *error;
        [SFHFKeychainUtils storeUsername:@"userName"
                             andPassword:[NSString stringWithFormat:@"%@",_emailTextField.text]
                          forServiceName:ClassRoom_URL
                          updateExisting:YES
                                   error:&error];
        BOOL saved = [SFHFKeychainUtils storeUsername:[NSString stringWithFormat:@"%@",_emailTextField.text] 
                                          andPassword:[NSString stringWithFormat:@"%@",_passWordTextField.text] 
                                       forServiceName:ClassRoom_URL
                                       updateExisting:YES 
                                                error:&error];
        if (!saved) {
                NSLog(@"密码保存错误！！！%@",error);
        }
        
        UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"提示" message:@"登录成功!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        al.tag = 111;
        [al show];
        [al release];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 111) {
        if (buttonIndex == 0) {
            [self dismissViewControllerAnimated:YES completion:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:Notification_REFURBISH_USERCENTERVIEW object:nil];
        }
    }
}

- (IBAction)setKeyBoardDown:(id)sender{
    
    [_emailTextField resignFirstResponder];
    [_passWordTextField resignFirstResponder];
    NSTimeInterval animationDuration = 0.30f;       
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];       
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0, 20, 320, 460);
    self.view.frame = rect;
   
}

-(IBAction)backgroundTap:(id)sender//点击背景
{
    [_emailTextField resignFirstResponder];
    [_passWordTextField resignFirstResponder];
    NSTimeInterval animationDuration = 0.30f;       
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];       
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0, 20, 320, 460);
    self.view.frame = rect;
    
    status=0;
}

- (IBAction)rememberThePassWord:(id)sender{
    NSError *error;
    checked = [SFHFKeychainUtils getPasswordForUsername:@"checked"
                                         andServiceName:ClassRoom_URL 
                                                  error:&error];
    if (nil != checked) {
        [SFHFKeychainUtils deleteItemForUsername:@"checked"
                                  andServiceName:ClassRoom_URL
                                           error:&error];
        checked = [SFHFKeychainUtils getPasswordForUsername:[NSString stringWithFormat:@"%@",_emailTextField.text]
                                                       andServiceName:ClassRoom_URL 
                                                                error:&error];
        [_rememberPassWord setImage:[UIImage imageNamed:@"checjed"] forState:UIControlStateNormal];
    }else {
            [SFHFKeychainUtils storeUsername:@"checked"    //key
                                 andPassword:@"checkedKey" //value
                              forServiceName:ClassRoom_URL
                              updateExisting:YES
                                       error:&error];
        [_rememberPassWord setImage:[UIImage imageNamed:@"checked"] forState:UIControlStateNormal];
    }
}

#pragma mark -

#pragma mark 解决虚拟键盘挡住UITextField的方法
- (void)keyboardWillShow:(NSNotification *)noti
{ 
}



-(BOOL)textFieldShouldReturn:(UITextField *)textField
{      
    return YES; 
}



- (void)textFieldDidBeginEditing:(UITextField *)textField
{       
    if(textField.tag==1) 
    {
        [_passWordTextField resignFirstResponder];
    }else {
        [_emailTextField resignFirstResponder];
    }
    
    if (status==0)
    {
        
        
        NSTimeInterval animationDuration2=0.3f;
        [UIView beginAnimations:@"ResizeForKeyboard" context:nil];       
        [UIView setAnimationDuration:animationDuration2];
        CGRect rect2 = CGRectMake(0, -20-69, 320, 460);
        self.view.frame = rect2;
        [UIView commitAnimations];
        status=1;
    }else {
        
        NSTimeInterval animationDuration2=0.0f;
        [UIView beginAnimations:@"ResizeForKeyboard" context:nil];       
        [UIView setAnimationDuration:animationDuration2];
            CGRect rect2 = CGRectMake(0, -20-69, 320, 460);
        self.view.frame = rect2;
        [UIView commitAnimations];
        status=1;
            
    }  
           
    
    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [_passWord release];
    [_emailName release];
    [_emailTextField release];
    [_passWordTextField release];
    [_weiboBarButtonItem release];
    [_renrenBarButtonItem release];
    [_QQBarButtonItem release];
    [_rememberPassWord release];
    [super dealloc];
}
@end
